<script setup lang="ts">
import { http } from '@/utils';
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { ref } from 'vue';
import base64ToBlob from 'b64-to-blob'
//获取个人信息数据
const profile = ref<ProfileInfo>({} as ProfileInfo)
const getProfile = async () => {
  try {
    showLoadingToast({
      message: '加载中...',
      duration: 0,
      forbidClick: true
    })
    const res = await http.get<MkResponse<ProfileInfo>>('member/profile')
    profile.value = res.data.result
    // console.log(res.data.result);
    birthday.value = res.data.result.birthday.split('-')
    profession.value[0] = res.data.result.profession
  } catch {
    console.log('请求失败');
  }
  finally {
    closeToast()
  }
}
getProfile()

//修改头像弹窗
const isShowTx = ref(false)
//点击头像弹窗选项的操作
const selectAvatar = async (action: ActionSheetAction, index: number) => {
  if (index === 0) {
    //拉起相册,选择图片后返回一个base64字符串
    const data = await mk.pickerPhoto()
    await onUpdateAvatar(data)
  } else {
    //拉起相机
    const data = await mk.pickerCamera()
    await onUpdateAvatar(data)
  }
}
//上传图片
const onUpdateAvatar = async (data: string) => {
  try {
    //把base64数据转成文件对象格式
    const image = base64ToBlob(data, 'image/jpeg')
    //创建formdata对象
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')
    showLoadingToast({
      message: '上传中...',
      duration: 0,
      forbidClick: true
    })
    //上传文件
    const res = await http.post<MkResponse<{ avatar: string }>>('/member/profile/avatar', fd)
    profile.value.avatar = res.data.result.avatar

    //修改原生的头像
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (e: any) {
    //错误
    showToast({ message: '上传失败' })
    console.log(e.message);

    closeToast()
  }
}

//修改生日弹窗
//选择生日双向绑定的值,没有接口数据使用默认的
const birthday = ref(['2000', '01', '01'])
const showBirthdayPopup = ref(false)
//点击确定操作
const changeBirthday = (value: { selectedValues: string[] }) => {
  //关闭弹窗
  showBirthdayPopup.value = false
  // return value.selectedValues as string[]
  profile.value.birthday = value.selectedValues.join('-')
}

//修改地区弹窗
const showAreaPopup = ref(false)

//获取地区数据
const areaCloumns = ref<AreaColumns>({} as AreaColumns)
const getAreaList = async () => {
  const res = await mk.getAreaColumns()
  areaCloumns.value = res
  // console.log(res);
}
// selectedValues: number[],
getAreaList()
const onSelectedLocation = (data: { selectedValues: number[] }) => {
  showAreaPopup.value = false
  console.log(data.selectedValues);
  const province = areaCloumns.value.province_list[data.selectedValues[0]]
  const city = areaCloumns.value.city_list[data.selectedValues[1]]
  const county = areaCloumns.value.county_list[data.selectedValues[2]]
  profile.value.fullLocation = `${province} ${city} ${county}`
}

// 4. 选择职业
const profession = ref<string[]>([])
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
  showProfessionPopup.value = false
  profile.value.profession = data.selectedValues[0]
}

/* 
保存资料
 */
//是否禁用按钮
const isShowLoding = ref(false)
const saveProfile = async () => {
  try {
    //禁用按钮
    isShowLoding.value = true
    //上传资料
    await http.put('/member/profile', profile.value)
    isShowLoding.value = false
    showToast({ message: '上传成功' })
  } catch (e) {
    showToast({ message: '上传失败' })
  } finally {
    isShowLoding.value = false
  }
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar">
      </van-image>
      <div class="avatar-btn">
        <span @click="isShowTx = true">修改头像</span>
      </div>
      <van-action-sheet v-model:show="isShowTx" :actions="[{ name: '相册' }, { name: '拍照' }]" cancel-text="取消"
        close-on-click-action @select="selectAvatar" />
    </div>
    <!-- 表单部分一组 -->
    <van-cell-group>
      <van-field label="账号" readonly v-model="profile.account"> </van-field>
      <van-field label="昵称" v-model="profile.nickname" placeholder="请输入昵称"> </van-field>
      <!-- 单元格 -->
      <van-cell title="性别" class="gender">
        <van-radio-group icon-size="16" v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" readonly placeholder="请选择日期" @click="showBirthdayPopup = true"
        v-model="profile.birthday"></van-field>
      <!-- 选择生日弹窗 -->
      <van-popup v-model:show="showBirthdayPopup" position="bottom">
        <!-- 日期 -->
        <van-date-picker v-model="birthday" title="选择日期" @cancel="showBirthdayPopup = false"
          :min-date="new Date('1980-01-01')" :max-date="new Date()" @confirm="changeBirthday" />
      </van-popup>
      <van-field label="所在地" readonly placeholder="请选择所在地" @click="showAreaPopup = true"
        v-model="profile.fullLocation"></van-field>
      <!-- 选择地区弹窗 -->
      <van-popup v-model:show="showAreaPopup" position="bottom">
        <!-- 地区数据 -->
        <van-area :area-list="areaCloumns" @confirm="onSelectedLocation"></van-area>
      </van-popup>
      <van-field label="职业" readonly placeholder="请选择职业" @click="showProfessionPopup = true"
        v-model="profession[0]"></van-field>
      <!-- 选择职业弹窗 -->
      <van-popup v-model:show="showProfessionPopup" position="bottom">
        <!-- 选择职业 -->
        <van-picker :columns="columns" @confirm="onChangeProfession" @cancel="showProfessionPopup = false"
          v-model="profession" />
      </van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button :loading="isShowLoding" :disabled="isShowLoding" round block type="primary" color="black"
        @click="saveProfile">
        保存资料
      </van-button>
    </div>

  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>